
import 'dart:ffi';

import 'package:dio/dio.dart';
import 'package:sjx/http/base_model.dart';
import 'package:sjx/repository/model/config_model.dart';
import 'package:sjx/repository/model/home_list_model.dart';
import 'package:sjx/repository/model/task_edit_detail_model.dart';
import 'package:sjx/repository/model/task_publish_process_model.dart';
import 'package:sjx/repository/model/task_status_number_model.dart';
import 'package:sjx/repository/model/task_submit_model.dart';
import 'package:sjx/repository/model/task_withdraw_record_model.dart';
import 'package:sjx/repository/model/user_info_model.dart';
import 'package:sjx/repository/model/user_model.dart';
import 'package:sjx/repository/model/user_task_publish_order_response.dart';
import 'package:sjx/repository/model/withdrawal_model.dart';
import 'package:sjx/utils/sp_utils.dart';

import '../http/dio_instance.dart';
import 'model/home_banner_model.dart';
import 'model/sale_coin_model.dart';
import 'model/task_detail_model.dart';
import 'model/task_process_step_model.dart';
import 'model/task_select_options_model.dart';
import 'model/user_task_order_response.dart';

class SJXApi {
  static SJXApi? _instance;

  SJXApi._internal();

  static SJXApi instance() {
    return _instance ??= SJXApi._internal();
  }

  ///获取首页banner数据
  Future<List<HomeBannerModel?>?> bannerList() async {
    Response response = await DioInstance.instance().get(path: "banner", param: {"bannerChannel": "task"});
    if (response.data is List) {
      return (response.data as List)
          .map((e) => HomeBannerModel.fromJson(e))
          .toList();
    } else {
      throw FormatException('Invalid banner data format');
    }
  }

  ///获取首页任务列表数据
  Future<HomeListModel?> homeList(int page) async {
    Response response = await DioInstance.instance().get(path: "task", param: {"size": 20, "page": page, "recommended": true});
    return HomeListModel.fromJson(response.data);
  }

  ///获取任务详情
  Future<TaskDetailModel> taskDetail(String taskNo) async {
    Response response = await DioInstance.instance().get(path: "task/$taskNo");
    return TaskDetailModel.fromJson(response.data);
  }

  ///获取手机号验证码
  Future<BaseModel> phoneCode(String phone) async {
    Response response = await DioInstance.instance().get(path: "user/$phone/sms");
    return BaseModel.fromJson(response.data);
  }

  ///验证码+手机号登录
  Future<bool> verifyCodeLogin(String phone, String code) async {
    Response response = await DioInstance.instance().post(path: "user", data: {"mobile": phone, "verifyCode": code});
    UserModel model = UserModel.fromJson(response.data);
    if (model.accessToken.isNotEmpty) {
      SpUtils.saveUserData(model);
      return true;
    }
    return false;
  }

  ///密码+手机号登录
  Future<bool> passwordLogin(String phone, String password) async {
    Response response = await DioInstance.instance().post(path: "user/login-with-mobile-password", queryParameters: {"mobile": phone, "password": password});
    UserModel model = UserModel.fromJson(response.data);
    if (model.accessToken.isNotEmpty) {
      SpUtils.saveUserData(model);
      return true;
    }
    return false;
  }

  ///注册账号
  Future<bool> register(String phone, String password, String code) async {
    Response response = await DioInstance.instance().post(path: "user/register-with-mobile-password", data: {"mobile": phone, "verifyCode": code, "password": password});
    UserModel model = UserModel.fromJson(response.data);
    if (model.accessToken.isNotEmpty) {
      SpUtils.saveUserData(model);
      return true;
    }
    return false;
  }

  ///获取用户信息
  Future<UserInfoModel> userInfo() async {
    final user = await SpUtils.getUserData();
    Response response = await DioInstance.instance().get(path: "user/${user?.platformId}");
    return UserInfoModel.fromJson(response.data);
  }

  ///获取用户金额
  Future<double> userAccount() async {
    final user = await SpUtils.getUserData();
    Response response = await DioInstance.instance().get(path: "user/${user?.platformId}/account");
    return response.data['availableAmount'];
  }

  ///获取用户各个任务状态数据
  Future<TaskStatusNumberModel> taskInfoNumber() async {
    final user = await SpUtils.getUserData();
    Response response = await DioInstance.instance().get(path: "user/${user?.platformId}/task-info");
    return TaskStatusNumberModel.fromJson(response.data);
  }

  ///领取任务
  Future<void> receiveTask(String taskId) async {
    final user = await SpUtils.getUserData();
    await DioInstance.instance().post(path: "task-order/${user?.platformId}/$taskId/bid", queryParameters: {"taskNo": taskId, "platformId": user?.platformId});
  }

  ///上传图片
  Future<String> uploadImage(String base64String) async {
    Response response = await DioInstance.instance().post(path: "image/base64", data: {"base64String": base64String});
    return response.data['uploadFileUrl'];
  }

  ///提交任务
  Future<void> submitTask(String orderNo,Map<String, dynamic> data) async {
    final user = await SpUtils.getUserData();
    await DioInstance.instance().post(path: "task-order/${user?.platformId}/${orderNo}/submit", data: data);
  }

  ///放弃任务
  Future<void> abandonTask(String orderNo) async {
    await DioInstance.instance().put(path: "task-order/${orderNo}/abandon");
  }

  ///删除任务
  Future<void> deleteTask(String taskNo) async {
    await DioInstance.instance().delete(path: "task/published/${taskNo}");
  }

  ///结束任务
  Future<void> endTask(String taskNo) async {
    await DioInstance.instance().delete(path: "task-management/${taskNo}/stop");
  }

  ///任务订单列表
  Future<UserTaskOrderResponse> taskOrder(int page, String status) async {
    Response response = await DioInstance.instance().get(path: "task-order", param: {"size": 20, "page": page, "taskOrderStatus": status});
    return UserTaskOrderResponse.fromJson(response.data);
  }

  ///发布任务订单列表
  Future<UserPublishTaskOrderResponse> publishTaskOrder(int page, String status) async {
    Response response = await DioInstance.instance().get(path: "task/user/published", param: {"size": 20, "page": page, "taskStatus": status});
    return UserPublishTaskOrderResponse.fromJson(response.data);
  }

  ///任务订单详情
  Future<TaskDetailModel> taskOrderDetail(String orderNo) async {
    Response response = await DioInstance.instance().get(path: "task-order/${orderNo}");
    return TaskDetailModel.fromJson(response.data);
  }

  ///任务进程
  Future<List<TaskProcessStepModel>?> taskOrderProcess(String orderNo) async {
    Response response = await DioInstance.instance().get(path: "task-order/${orderNo}/process");
    List<dynamic> dataList = response.data;
    List<TaskProcessStepModel> steps = dataList
        .map((json) => TaskProcessStepModel.fromJson(json))
        .toList();
    return steps;
  }

  ///任务已提交内容
  Future<TaskSubmitModel> taskSubmitDetail(String orderNo) async {
    Response response = await DioInstance.instance().get(path: "task-order/${orderNo}/submit-info");
    return TaskSubmitModel.fromJson(response.data);
  }

  ///任务配置
  Future<TaskConfigModel> taskConfiguration() async {
    Response response = await DioInstance.instance().get(path: "task/configuration");
    return TaskConfigModel.fromJson(response.data);
  }

  ///创建任务选项
  Future<TaskSelectOptionsModel> taskCreateSelectOptions(String categoryName) async {
    Response response = await DioInstance.instance().get(path: "task/select-options", param: {"categoryName": categoryName});
    if (response.data == null) {
      throw Exception('响应数据为空');
    }
    TaskSelectOptionsModel model = TaskSelectOptionsModel.fromJson(response.data);
    return model;
  }

  ///发布任务
  Future<String> createTask(Object data) async {
    Response response = await DioInstance.instance().post(path: "task", data: data);
    return response.data['taskNo'];
  }

  ///修改任务
  Future<String> editTask(Object data, String taskId) async {
    Response response = await DioInstance.instance().put(path: "task/published/$taskId", data: data);
    return response.data['taskNo'];
  }

  ///余额抵扣
  Future<void> payBalance(double deductAmount, String taskId) async {
    await DioInstance.instance().post(path: "payment/$taskId/balance", queryParameters: {"deductAmount": deductAmount});
  }

  ///重新发布任务获取任务详情
  Future<TaskEditDetailModel> taskPublishDetail(String taskId) async {
    Response response = await DioInstance.instance().get(path: "task/published/$taskId");
    return TaskEditDetailModel.fromJson(response.data);
  }

  ///任务审核状态统计
  Future<Map<String, dynamic>> taskPublishOrderStatics(String taskId) async {
    Response response = await DioInstance.instance().get(path: "task/published/$taskId/order-statics");
    return response.data;
  }

  ///发布者任务审核列表
  Future<Map<String, dynamic>> taskPublishOrder(String taskId, int page, String status) async {
    Response response = await DioInstance.instance().get(path: "task/published/$taskId/orders", param: {"size": 20, "page": page, "orderStatus": status, "sortValues": "createTime-ASC"});
    return response.data;
  }

  ///加入黑名单
  Future<void> setBlackList(String platformId) async {
    await DioInstance.instance().post(path: "user/black-list/$platformId");
  }

  ///发布者通过任务
  Future<void> taskManagementPass(String orderNo) async {
    await DioInstance.instance().put(path: "task-management/task-order/$orderNo", param: {"orderNo": orderNo, "verifyStatus": "通过"});
  }

  ///发布者拒绝任务
  Future<void> taskManagementReject(String orderNo, String comment) async {
    await DioInstance.instance().put(path: "task-management/task-order/$orderNo", param: {"orderNo": orderNo, "verifyStatus": "拒绝", "comment": comment});
  }

  ///发布者任务进程
  Future<TaskPublishProcessModel> taskPublishProcess(String taskNo) async {
    Response response = await DioInstance.instance().get(path: "task/published/${taskNo}/process-result");
    return TaskPublishProcessModel.fromJson(response.data);
  }

  ///意见反馈
  Future<void> feedback(String content) async {
    final user = await SpUtils.getUserData();
    await DioInstance.instance().post(path: "user/${user?.platformId}/feedback", queryParameters: {"platformId": user?.platformId, "userFeedbackContent": content});
  }

  ///更新用户信息
  Future<void> updateUserInfo(Object data) async {
    final user = await SpUtils.getUserData();
    await DioInstance.instance().put(path: "user/${user?.platformId}", data: data);
  }

  ///用户提现账户
  Future<WithdrawalModel> userWithdrawAccountInfo() async {
    final user = await SpUtils.getUserData();
    Response response = await DioInstance.instance().get(path: "user/${user?.platformId}/account-info");
    return WithdrawalModel.fromJson(response.data);
  }

  ///校验验证码
  Future<void> verifySmsCode(String mobile, String verifyCode) async {
    await DioInstance.instance().post(path: "user/sms-code", queryParameters: {"mobile": mobile, "verifyCode": verifyCode});
  }

  ///绑定支付宝账户信息
  Future<void> bandAlipayAccountInfo(Object data) async {
    final user = await SpUtils.getUserData();
    await DioInstance.instance().post(path: "user/${user?.platformId}/alipay-setting", data: data);
  }

  ///提交提现申请
  Future<void> applyWithdraw(Object data) async {
    final user = await SpUtils.getUserData();
    await DioInstance.instance().post(path: "user/${user?.platformId}/withdraw", data: data);
  }

  ///提交提现申请-无须验证码
  Future<void> applyWithdrawNotCode(Map<String, dynamic> param) async {
    final user = await SpUtils.getUserData();
    await DioInstance.instance().post(path: "user/${user?.platformId}/withdraw-without-accountinfo", queryParameters: param);
  }

  ///现金交易流水
  Future<Response> userExchanges(Map<String, dynamic> param) async {
    final user = await SpUtils.getUserData();
    return await DioInstance.instance().get(path: "user/${user?.platformId}/exchanges", param: param);
  }

  ///金币交易流水
  Future<Response> userExchangesCoin(Map<String, dynamic> param) async {
    final user = await SpUtils.getUserData();
    return await DioInstance.instance().get(path: "user/${user?.platformId}/coin-exchanges", param: param);
  }

  ///金币数量
  Future<SaleCoinModel> userCoinAmount() async {
    final user = await SpUtils.getUserData();
    Response response =  await DioInstance.instance().get(path: "user/${user?.platformId}/coin-convert");
    return SaleCoinModel.fromJson(response.data);
  }

  ///出售金币
  Future<void> userSaleCoin(Map<String, dynamic> param) async {
    final user = await SpUtils.getUserData();
    await DioInstance.instance().post(path: "user/${user?.platformId}/coin-convert", queryParameters: param);
  }

  ///支付宝支付
  Future<Response> alipayOrder(double deductAmount, String taskNo) async {
    return await DioInstance.instance().post(path: "payment/${taskNo}", queryParameters: {'deductAmount': deductAmount});
  }

  ///微信支付
  Future<Response> wechatOrder(double deductAmount, String taskNo) async {
    return await DioInstance.instance().post(path: "payment/wechat/${taskNo}", queryParameters: {'deductAmount': deductAmount});
  }
}